//
// Created by xili on 2024/8/29 11:45.
// GO BIG OR GO HOME.
//
#include "leetcode.h"

class Solution {
public:
    vector<int> findClosestElements(vector<int> &arr, int k, int x) {
        vector<int> ans;
        int close = lower_bound(arr.begin(), arr.end(), x) - arr.begin();
        int n = arr.size();
        int l = close - 1, r = close;
        while (k--) {
            if (l >= 0 && r < n) {
                ans.push_back(abs(x - arr[l]) - abs(x - arr[r]) <= 0 ? arr[l--] : arr[r++]);
            } else if (l >= 0) {
                ans.push_back(arr[l--]);
            } else {
                ans.push_back(arr[r++]);
            }
        }
        sort(ans.begin(), ans.end());
        return ans;
    }
};